import sys

def parse_channel(columns):
    notes = []
    prev_note = None
    duration = 0

    for row in columns:
        note = row.strip()
        if note == "---":
            duration += 1
        else:
            if prev_note:
                notes.append((prev_note, duration))
            prev_note = note
            duration = 1
    if prev_note:
        notes.append((prev_note, duration))

    return notes

def clean_note(note):
    if note.lower().startswith('r'):
        return 'r'
    return note.lower().replace('-', '')

def format_note(note, duration, frames_per_row):
    clean = clean_note(note)
    return f"{clean}/{duration * frames_per_row}"

def process_vtp_file(filename, frames_per_row, canales):
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    ch_a = [line[8:11] for line in lines]
    ch_b = [line[22:25] for line in lines]
    ch_c = [line[36:39] for line in lines]

    parsed_a = parse_channel(ch_a)
    parsed_b = parse_channel(ch_b)
    parsed_c = parse_channel(ch_c)

    result = []

    if 'a' in canales:
        result.append("[CANAL A]")
        result += [format_note(n, d, frames_per_row) for n, d in parsed_a]

    if 'b' in canales:
        result.append("\n[CANAL B]")
        result += [format_note(n, d, frames_per_row) for n, d in parsed_b]

    if 'c' in canales:
        result.append("\n[CANAL C]")
        result += [format_note(n, d, frames_per_row) for n, d in parsed_c]

    return '\n'.join(result)

def main():
    if len(sys.argv) < 4:
        print("Uso: python simplificar_vtp.py <frames_por_fila> <archivo_entrada.vtp> <archivo_salida.txt> [canales]")
        sys.exit(1)

    try:
        frames_per_row = int(sys.argv[1])
    except ValueError:
        print("[ERROR] El primer argumento debe ser un número entero (frames por fila).")
        sys.exit(1)

    archivo_entrada = sys.argv[2]
    archivo_salida = sys.argv[3]
    canales = sys.argv[4].lower() if len(sys.argv) > 4 else 'abc'

    output = process_vtp_file(archivo_entrada, frames_per_row, canales)
    with open(archivo_salida, 'w', encoding='utf-8') as f:
        f.write(output)
    print(f"[✔] Archivo guardado como: {archivo_salida} (canales: {canales.upper()})")

if __name__ == "__main__":
    main()
